package edu.xpu.project.user.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.xpu.project.user.entity.ExamPlaceEntity;
import edu.xpu.project.user.repository.ExamPlaceRepository;

@Service
@Transactional(readOnly=true)
public class ExamPlaceServiceImpl implements ExamPlaceService {
	
	@Autowired
	private ExamPlaceRepository examPlaceRepository;

	@Override
	public ExamPlaceEntity get(Long id) {
		return examPlaceRepository.findOne(id);
	}

	@Transactional(readOnly=false)
	@Override
	public ExamPlaceEntity saveOrUpdate(ExamPlaceEntity t) {
		String examPlaceName = t.getExamPlaceName();
		ExamPlaceEntity byExamPlaceName = getByExamPlaceName(examPlaceName);
		if (byExamPlaceName == null) {
			byExamPlaceName = examPlaceRepository.saveAndFlush(t);
		}
		return byExamPlaceName;
	}

	@Transactional(readOnly=false)
	@Override
	public void delete(Long id) {
		examPlaceRepository.delete(id);
	}

	@Override
	public ExamPlaceEntity getByExamPlaceName(String examPlaceName) {
		return examPlaceRepository.findByExamPlaceName(examPlaceName);
	}

	@Override
	public Page<ExamPlaceEntity> getPageByCriterias(String pageNumberStr, String pageSizeStr, final ExamPlaceEntity placeEntity) {
			Integer pageNumber = 1;
			Integer pageSize = 10;
			try {
				pageNumber = Integer.parseInt(pageNumberStr);
			} catch (Exception e) {}
			try {
				pageSize = Integer.parseInt(pageSizeStr);
			} catch (Exception e) {}
			Pageable pageable = new PageRequest(pageNumber - 1, pageSize);
			
			return examPlaceRepository.findAll(new Specification<ExamPlaceEntity>() {
				@Override
				public Predicate toPredicate(Root<ExamPlaceEntity> root, CriteriaQuery<?> query,
						CriteriaBuilder builder) {
					if (placeEntity == null) {
						return null;
					}
					//添加查询条件
					List<Predicate> predicates = new ArrayList<Predicate>(3);
					
					
					if (predicates.size() == 0) {
						return null;
					}
					Predicate[] predArr= new Predicate[predicates.size()];
					return builder.and(predicates.toArray(predArr));
				}
			}, pageable);
	}

}
